<template>
  <div>
    <el-upload
      v-loading="loading"
      element-loading-text="上传中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-change="onChange"
      :http-request="handleRequest"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :limit="limit"
      :class="limit === fileList.length ? 'hideAdd' : ''"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览图片" :visible.sync="dialogVisible">
      <img :src="imgSrc" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDvqofP1vkV9XqV4lNtHWedUCnHdrwMfqv',
  SecretKey: 'JVZUHyW2Sp5FJGGAPfr19DB3Ohw5762q'
})
export default {
  name: 'ImageUpload',
  components: {},
  props: {
    // eslint-disable-next-line
    onRequestSelf: Function,
    // 限制张数
    limit: {
      type: Number,
      default: 1
    },
    // eslint-disable-next-line
    beforeUploadSelf: Function,
    // eslint-disable-next-line
    onSuccess: Function,
  },
  data() {
    return {
      fileList: [],
      imgSrc: '',
      dialogVisible: false,
      loading: false
    }
  },
  methods: {
    // 上传文件后同步
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 覆盖默认action,自己编写图片存储位置
    handleRequest(data) {
      if (this.onRequestSelf) {
        this.onRequestSelf(data)
        return
      }
      this.loading = true
      cos.putObject({
        Bucket: 'wxfhrsaas-1314927305', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: function(progressData) {
          // console.log(JSON.stringify(progressData))
          // 这个就是上传的百分比
          // params.percent 表示当前上传的进度
        }
      }, (err, data) => {
        // 错误处理
        if (err || data.statusCode !== 200) {
          this.$message.danger('图片上传失败，请重新上传')
        } else {
          this.onSuccess && this.onSuccess({ url: 'https://' + data.Location })
        }
        this.loading = false
      })
    },
    // 图片移除时触发，保持数据同步
    handleRemove(file, fileList) {
      this.fileList = fileList
      console.log(fileList)
    },
    // 图片预览触发方法
    handlePreview(file) {
      this.dialogVisible = true
      this.imgSrc = file.url
    },
    // 上传图片前的校验
    beforeUpload(file) {
      // 如果有自定义校验函数的话，就去判断，函数返回一个卜尔值，因此可以直接return
      if (this.beforeUploadSelf) {
        return this.beforeUploadSelf()
      }
      const fileType = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png', 'image/svg+xml']
      if (!fileType.includes(file.type)) {
        this.$message.warning('文件格式错误，请重试')
        return false
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.warning('文件大小不能超过5M，请重试')
        return false
      }
      return true
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-dialog__body {
  text-align: center;
}
.hideAdd {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
